import { useCallback, useState, useEffect, useRef } from "react";
// import { useSelector } from "react-redux";
import { useDispatchUser } from "@/hooks/user";
import { RegisterData } from "@/types/userType"; // 假设你有一个 RegisterData 类型来保存注册表单数据
import {Form, Input, Button, Field, Cell, Toast, Image, Flex, Navbar, Avatar} from "@taroify/core";
import { BaseEventOrig, FormProps, View, Text } from "@tarojs/components";
import Taro from "@tarojs/taro";
// import { RootState } from "@/stores";
import {ArrowLeft, EyeOutlined} from "@taroify/icons";
import appIcon from '@/assets/images/virtual_teacher_icon.png'
import {registerUser} from "@/api/auth";
import {uploadFile} from "@/api/upload";
import './index.css';



function Register() {
  const windowInfo = Taro.getWindowInfo();
  const statusBarHeight = windowInfo.statusBarHeight;
  const [btnLoad, setBtnLoad] = useState(false);
  const [passwordVisible, setPasswordVisible] = useState(false); // 密码可见性状态
  const [confirmPasswordVisible, setConfirmPasswordVisible] = useState(false); // 确认密码可见性状态
  // const captchaSrc = useSelector((state: RootState) => state.user.captcha);
  const { getCaptcha } = useDispatchUser();
  const hasFetchedCaptcha = useRef(false);

  // 刷新验证码
  const refreshCaptcha = useCallback(() => {
    getCaptcha();
  }, [getCaptcha]);

  // 初始化时获取验证码
  useEffect(() => {
    if (!hasFetchedCaptcha.current) {
      refreshCaptcha();
      hasFetchedCaptcha.current = true;
    }
  }, [refreshCaptcha]);

  // 切换密码可见性
  const togglePasswordVisibility = () => {
    setPasswordVisible(!passwordVisible);
  };

  const toggleConfirmPasswordVisibility = () => {
    setConfirmPasswordVisible(!confirmPasswordVisible);
  };

  // 表单提交
  const onSubmit = async (event: BaseEventOrig<FormProps.onSubmitEventDetail>) => {
    const values = event.detail.value as RegisterData;
    setBtnLoad(true);

    const data = {username: values.username, captcha: "1234", password: values.password};
    registerUser(data)
      .then(() => {
        Taro.showToast({
          title: '注册成功，请登录！',
          icon: 'success',
          duration: 2000,
        });
        Taro.navigateTo({
          url: '/pages/auth/login/index', // 跳转到登录页面
        });
      })
      .catch((error) => {
        setBtnLoad(false);
        Taro.showToast({
          title: error.message || '注册失败，请重试！',
          icon: 'error',
          duration: 2000,
        });
      });
  };

  const handleLogin = async ()=> {
    await Taro.redirectTo({
      url: '/pages/auth/login/index',
    });
  }

  const handleBackHome = async ()=> {
    await Taro.redirectTo({
      url: '/pages/tabs/dialogue/index', // 跳转到登录页面
    });
  }

  const [avatar, setAvatar] = useState('')
  const onChooseAvatar = async (e) => {
    setAvatar(e.detail.avatarUrl)
    await uploadAvatar(e.detail.avatarUrl)
  }

  // 上传头像到服务器
  const uploadAvatar = async (file) => {
    const res = await uploadFile(file.path);
    setAvatar(res.url)
  }

  return (
    <View style={{ height: '100vh', width: '100wv', background: 'linear-gradient(-225deg, #2CD8D5 0%, #C5C1FF 56%, #FFBAC3 100%)' }}>
      <Navbar
        fixed
        style={{
          paddingTop: `${(statusBarHeight || 0) + 50}rpx`,
          boxShadow: '0 2rpx 10rpx rgba(0, 0, 0, 0.1)',
        }}
      >
        <Navbar.NavLeft icon={<ArrowLeft onClick={handleBackHome} size={25} color='black' />} />
        <Navbar.Title style={{ fontSize: '35rpx', color: 'black' }}>注册</Navbar.Title>
      </Navbar>
      <Flex justify='center' align='center' direction='column' style={{ height: '100%', width: '100%' }}>
        <View>
          <Image
            src={appIcon}
            style={{width: '300rpx', height: '300rpx',}}
          />
        </View>
        <Form onSubmit={onSubmit}>
          <Toast id='toast' />
          <Cell.Group inset>
            {/* 头像 */}
            <Field
              label='头像'
              name='avatar'
              rules={[{ required: true, message: "请上传头像" }]}
            >
              <Button
                open-type='chooseAvatar'
                onChooseAvatar={onChooseAvatar}
                style={{border: '0'}}
              >
                <Avatar src={avatar} />
              </Button>
            </Field>

            {/* 用户名 */}
            <Field
              label='用户名'
              name='username'
              rules={[{ required: true, message: "请填写用户名" }]}
            >
              <Input placeholder='请输入用户名' />
            </Field>

            {/* 密码 */}
            <Field
              label='密码'
              name='password'
              rules={[{ required: true, message: "请填写密码" }]}
              rightIcon={passwordVisible ? (
                <EyeOutlined
                  onClick={togglePasswordVisibility}
                  style={{ cursor: 'pointer', color: 'inherit' }}
                />
              ) : (
                <EyeOutlined
                  onClick={togglePasswordVisibility}
                  style={{ cursor: 'pointer', color: 'inherit' }}
                />
              )}
            >
              <Input placeholder='请输入密码' />
            </Field>

            {/* 确认密码 */}
            <Field
              label='确认密码'
              name='confirmPassword'
              rules={[{ required: true, message: "请确认密码" }]}
              rightIcon={confirmPasswordVisible ? (
                <EyeOutlined
                  onClick={toggleConfirmPasswordVisibility}
                  style={{ cursor: 'pointer', color: 'inherit' }}
                />
              ) : (
                <EyeOutlined
                  onClick={toggleConfirmPasswordVisibility}
                  style={{ cursor: 'pointer', color: 'inherit' }}
                />
              )}
            >
              <Input placeholder='请确认密码' />
            </Field>

            {/* 验证码 */}
            {/*<Field*/}
            {/*  label='验证码'*/}
            {/*  name='captcha'*/}
            {/*  rules={[{ required: true, message: "请填写验证码" }]}*/}
            {/*>*/}
            {/*  <Input placeholder='请输入验证码' />*/}
            {/*  <Image*/}
            {/*    src={captchaSrc}*/}
            {/*    alt='验证码'*/}
            {/*    onClick={refreshCaptcha}*/}
            {/*    style={{ cursor: 'pointer', height: '32px', width: 'auto', marginLeft: '10px' }}*/}
            {/*  />*/}
            {/*</Field>*/}
            <Cell>
              <Text>已有账号，前去</Text><Text onClick={handleLogin} style={{cursor: 'pointer', color: 'blue'}}>登录</Text>
            </Cell>
          </Cell.Group>

          {/* 提交按钮 */}
          <View style={{ margin: '16px' }}>
            <Button
              shape='round'
              block
              color='primary'
              formType='submit'
              loading={btnLoad}
            >
              注册
            </Button>
          </View>
        </Form>

      </Flex>
    </View>
  );
}

export default Register;
